#include "qprojectresource.h"

#include "qresourceregister.h"
#include "qresourcefile.h"

using namespace SHAREDLIB;

QProjectResource* QProjectResource::m_resource=NULL;

QProjectResource::QProjectResource(QObject *parent) :
    QObject(parent),
    m_file(new QResourceFile)
{
    m_file->setFileName("resource");
}

QProjectResource::~QProjectResource()
{
    delete m_file;
}

void QProjectResource::load(const QString &path)
{
    m_file->load(path);
    m_resourceNumber.clear();
    if(SHAREDLIB::QResourceRegister::reg(m_file))
    {
        QStringList names=m_file->resourceNames();
        foreach(QString name,names)
        {
            m_resourceNumber.insert(name,1);
        }
    }

}

void QProjectResource::save(const QString &path)
{
    m_file->save(path);
}

void QProjectResource::clear()
{
    QResourceRegister::unreg();
    m_file->clear();
    m_resourceNumber.clear();
}

QProjectResource* QProjectResource::resource()
{
    if(m_resource==NULL)
    {
        m_resource=new QProjectResource();
    }
    return m_resource;
}

void QProjectResource::release()
{
    if(m_resource!=NULL)
    {
        delete m_resource;
        m_resource=NULL;
    }
}

void QProjectResource::addResource(const QString &name, const QByteArray &data)
{
    int k=m_resourceNumber.value(name,0);
    k++;
    if(k==1)
    {
        m_file->addResource(name,data);
        QResourceRegister::reg(m_file);
    }
    m_resourceNumber.insert(name,k);
}

void QProjectResource::removeResource(const QString &name)
{
    int k=m_resourceNumber.value(name);
    k--;
    if(k==0)
    {
        m_file->removeResource(name);
        if(m_file->resourceCount()>0)
        {
            QResourceRegister::reg(m_file);
        }
        else
        {
            QResourceRegister::unreg();
        }
        m_resourceNumber.remove(name);
    }
    else
    {
        m_resourceNumber.insert(name,k);
    }
}
